package com.yiqi.liebang.feature.news.view;


import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.suozhang.framework.component.http.RxDataProcessFactory;
import com.suozhang.framework.component.recyclerview.DividerItemDecoration;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseFragment;
import com.suozhang.framework.framework.Callback;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.widget.EmptyView;
import com.yiqi.liebang.R;
import com.yiqi.liebang.entity.bo.PeopleBo;
import com.yiqi.liebang.entity.bo.VisitorBo;
import com.yiqi.liebang.feature.home.view.AddSuccessActivity;
import com.yiqi.liebang.feature.login.view.LoginActivity;
import com.yiqi.liebang.feature.mine.view.UserInfoActivity;
import com.yiqi.liebang.feature.news.contract.VisitorContract;
import com.yiqi.liebang.feature.news.dependencies.visitor.DaggerVisitorComponent;
import com.yiqi.liebang.feature.news.dependencies.visitor.VisitorPresenterModule;
import com.yiqi.liebang.feature.news.view.adapter.VistorAdapter;
import com.yiqi.liebang.framework.api.UserApi;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * A simple {@link Fragment} subclass.
 */
public class VisitorsFragment extends BaseFragment implements VisitorContract.View, OnRefreshListener, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener, BaseQuickAdapter.OnItemChildClickListener {


    @BindView(R.id.rv_people)
    RecyclerView mRvVisitor;

    @Inject
    VisitorContract.Presenter mPresenter;
    @BindView(R.id.smartRefesh)
    SmartRefreshLayout mSmartRefesh;

    private VistorAdapter mAdapter;
    private EmptyView mEmptyView;
    private int pageIndex = 1;
    private int pageSize = 10;
    List<VisitorBo> mData;


    @Override
    public int attachLayoutRes() {
        return R.layout.fragment_visitors;
    }

    @Override
    protected void initInjector() {
        DaggerVisitorComponent.builder().visitorPresenterModule(new VisitorPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        initAdapter();
    }

    @Override
    protected void initData() {
        if (!AM.user().isLogin()) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
        }else {
            pageIndex = 1;
            mPresenter.getVisitorList(pageIndex, pageSize);
        }

    }

    @Override
    protected void initEvent() {

    }

    private void initAdapter() {
        mSmartRefesh.setEnableLoadMore(false);
        mSmartRefesh.setOnRefreshListener(this);
        mEmptyView = new EmptyView(mRvVisitor);
        mRvVisitor.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvVisitor.addItemDecoration(new DividerItemDecoration(DividerItemDecoration.VERTICAL).setHeight(2));
        mAdapter = new VistorAdapter();
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        mAdapter.bindToRecyclerView(mRvVisitor);
        mAdapter.setNewData(null);
        mAdapter.setOnLoadMoreListener(this, mRvVisitor);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setCommonCallback(new Callback.CommonCallback() {
            @Override
            public void onSubscribe(Disposable d) {
                showLoading(d);
            }

            @Override
            public void onSuccess(Object result) {
                dismissLoading();
            }

            @Override
            public void onError(Throwable ex) {
                dismissLoading();
            }

            @Override
            public void onComplete() {
                dismissLoading();
            }
        });
    }

    @Override
    public void showVisitorListSuccess(List<VisitorBo> workBoPageData) {
        mSmartRefesh.finishRefresh();
        mData = workBoPageData;
        setData(true, mData);
        mAdapter.setEnableLoadMore(true);
    }

    @Override
    public void showVisitorListError(String error) {
        if (mSmartRefesh != null) mSmartRefesh.finishRefresh();
        mAdapter.setEmptyView(mEmptyView.getErrorView(error));
        mAdapter.setNewData(null);
        mAdapter.setEnableLoadMore(true);
        mSmartRefesh.finishRefresh();
    }

    @Override
    public void showVisitorListMoreSuccess(List<VisitorBo> msg) {
        setData(false, msg);
    }

    @Override
    public void showVisitorListMoreError(String msg) {
        mAdapter.loadMoreFail();
    }

    @Override
    public void showVisitorListEmpty() {
        if (mSmartRefesh != null) mSmartRefesh.finishRefresh();
        mAdapter.setEmptyView(mEmptyView.getEmptyView());
        mAdapter.setNewData(null);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refresh();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent = new Intent(getActivity(), UserInfoActivity.class);
        intent.putExtra("is_view_my", false);
        intent.putExtra("visitorUid", mData.get(position).getUserUid());
        startActivity(intent);
    }

    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }


    private void refresh() {
        mAdapter.setEnableLoadMore(false);//这里的作用是防止下拉刷新的时候还可以上拉加载
        initData();
    }

    private void loadMore() {
        mPresenter.getVisitorListMore(pageIndex, pageSize);
    }

    private void setData(boolean isRefresh, List data) {
        pageIndex++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mAdapter.addData(data);
            }
        }
        if (size < pageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mAdapter.loadMoreEnd(isRefresh);
        } else {
            mAdapter.loadMoreComplete();
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        PeopleBo peopleBo = new PeopleBo();
        peopleBo.setApplicationUserUid(mAdapter.getData().get(position).getUserUid());

        AM.api().createApiService(UserApi.class)
                .getAddFriend(peopleBo)
                .compose(RxDataProcessFactory.dataPrepAndIoToMainTransformer())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading(d);
                    }

                    @Override
                    public void onNext(String s) {
                        dismissLoading();
                        Intent intent = new Intent(getActivity(), AddSuccessActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onError(Throwable e) {
                        dismissLoading();
                        T.showShort(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        dismissLoading();
                    }
                });
    }
}
